//
//  DDOrderListViewController.m
//  Dingdong
//
//  Created by 程强 on 16/11/15.
//  Copyright © 2016年 程强. All rights reserved.
//

#import "DDOrderListViewController.h"
#import "DDOrderTableCell.h"
#import "DDOrderSectionFooter.h"
#import "DDOrderSectionHeader.h"
#import "DDEvaluateViewController.h"
#import "KSTabButtonView.h"
#import "DDOrderManager.h"
#import "DDOrderSet.h"
#import "MJRefresh.h"
#import "DDOrderDetailsViewController.h"
#import "UIAlertView+Click.h"
#import "DDGoodsDetailsViewController.h"
#import "DDCancelOrderReasonView.h"

@interface DDOrderListViewController ()<UITableViewDelegate,UITableViewDataSource,KSTabButtonViewDelegate,UIAlertViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *orderTable;
@property (weak, nonatomic) IBOutlet UIView *tabBackView;
@property (strong, nonatomic) KSTabButtonView *tabView;
@property (strong, nonatomic) DDOrderManager *manager;
@property (strong, nonatomic) DDOrderSet *orderSet;
@property (strong, nonatomic) NSString *selectedOrderStatus;
@property (nonatomic) NSInteger currentPage;
@end

@implementation DDOrderListViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self headerRefresh];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.manager = [DDOrderManager new];
    [self layoutOrderView];
}
- (void)setRefresh
{
    weak_Self(self);
    MJRefreshHeader *header =[MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf headerRefresh];
    }];
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [weakSelf footerRefresh];
    }];
    [self.orderTable setMj_header:header];
    [self.orderTable setMj_footer:footer];
}
- (void)layoutOrderView
{
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self setRefresh];
    self.tabView = [[KSTabButtonView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 50)];
    [self.tabBackView addSubview:_tabView];
    _tabView.delegate = self;
    _tabView.items = @[@"All Orders",@"Unpaid",@"Shipped",@"Complete"];
    
    if (_orderStatus == kOrderStatusPending) {
        _tabView.currentSelectIndex = 1;
    }else if (_orderStatus == kOrderStatusShipped) {
        _tabView.currentSelectIndex = 2;
    }else if (_orderStatus == kOrderStatusComplete){
        _tabView.currentSelectIndex = 3;
    }else if (_orderStatus == kOrderStatusAll){
        _tabView.currentSelectIndex = 0;
    }
}
- (void)setOrderStatus:(kOrderStatus)orderStatus
{
    _orderStatus = orderStatus;
    
    if (orderStatus == kOrderStatusPending) {
        self.selectedOrderStatus = @"wait_pay";
    }else if (orderStatus == kOrderStatusShipped) {
        self.selectedOrderStatus = @"wait_rog";
    }else if (orderStatus == kOrderStatusComplete){
        self.selectedOrderStatus = @"5";
    }else if (orderStatus == kOrderStatusAll){
        self.selectedOrderStatus = @"";
    }
}
- (void)headerRefresh
{
    weak_Self(self);
    [self fetchOrderList:self.selectedOrderStatus pull:YES complete:^{
        [weakSelf.orderTable.mj_header endRefreshing];
    }];
}
- (void)footerRefresh
{
    weak_Self(self);
    [self fetchOrderList:self.selectedOrderStatus pull:NO complete:^{
        [weakSelf.orderTable.mj_footer endRefreshing];
    }];
}
- (void)ksTabButtonView:(KSTabButtonView *)tabView didSelectIndex:(NSInteger)index
{
    if (index == 1) {
        self.orderStatus = kOrderStatusPending;
    }else if (index == 2){
        self.orderStatus = kOrderStatusShipped;
    }else if (index == 3){
        self.orderStatus = kOrderStatusComplete;
    }else if (index == 0){
        self.orderStatus = kOrderStatusAll;
    }
    [self headerRefresh];
}
#pragma mark --- 接口
- (void)fetchOrderList:(NSString *)type pull:(BOOL)pull complete:(void(^)())block
{
    weak_Self(self);
    if (pull) {
        self.currentPage = 1;
    }
    [self showHUD];
    [[self.manager getOrderList:type pageNumber:self.currentPage pageSize:kPageSize]subscribeNext:^(id x) {
        if (pull) {
            weakSelf.orderSet = x;
        }else{
            DDOrderSet *set = x;
            [weakSelf.orderSet.orderAry addObjectsFromArray:set.orderAry];
        }
        if (weakSelf.orderSet.orderAry.count == 0) {
            [weakSelf showNoContentViewWithOriginY:65+51 image:@"no_order" message:@"You haven't had your order yet."];
        }else{
            [weakSelf hideNoContentView];
        }
        [weakSelf.orderTable reloadData];
        weakSelf.currentPage+=1;
    } error:^(NSError *error) {
        
    } completed:^{
        if (block) {
            block();
        }
        [weakSelf hideHUD];
    }];
}
- (void)confirmOrderClick:(NSNumber *)order_id success:(void(^)())block
{
    [[self.manager confirmOrder:order_id]subscribeNext:^(id x) {
        if (block) {
            block();
        }
    } error:^(NSError *error) {
        NSString *msg = error.userInfo[@"msg"];
        [self showMessageHUD:msg delayHide:1.0];
    } completed:^{
        
    }];
}
- (void)deleteOrderClick:(NSNumber *)order_id success:(void(^)())block
{
    [[self.manager deleteOrder:order_id]subscribeNext:^(id x) {
        if (block) {
            block();
        }
    } error:^(NSError *error) {
        NSString *msg = error.userInfo[@"msg"];
        [self showMessageHUD:msg delayHide:1.0];
    } completed:^{
        
    }];
}
- (void)cancelOrderClick:(NSNumber *)order_id reason:(NSString *)reason success:(void(^)())block
{
    [[self.manager cancelOrder:order_id reason:reason]subscribeNext:^(id x) {
        if (block) {
            block();
        }
    } error:^(NSError *error) {
        
    } completed:^{
        
    }];
}
#pragma mark --- TableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.orderSet.orderAry.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    DDOrderObj *order = self.orderSet.orderAry[section];
    return order.orderItemGoodsList.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 120.0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 54.0;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    DDOrderObj *order = self.orderSet.orderAry[section];
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 48)];
    DDOrderSectionFooter *footer = [[DDOrderSectionFooter alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 44)];
    footer.orderStatus = [DDOrderInfo mappingOrderStatus:order.order.status];
    [view addSubview:footer];
    view.backgroundColor = RGBColor(244, 244, 244);
    [footer setOrderOperation:^{

    } right:^{
        if (footer.orderStatus == kOrderStatusShipped) {
            //确认收货
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Do you receive your goods" message:nil delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Done", nil];
            [alert show];
            [alert click:^(NSInteger buttonIndex) {
                if (buttonIndex == 1) {
                    [self confirmOrderClick:order.order.order_id success:^{
                        order.order.status = @4;
                        [tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationNone];
                    }];
                }
            }];
            

        }else if (footer.orderStatus == kOrderStatusPending){
            //取消订单
            DDCancelOrderReasonView *cancelView = [[DDCancelOrderReasonView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
            cancelView.reasonAry = @[@"Do not want to buy now",@"Commodity prices are more expensive",@"Repeat the order",@"Incorrect receipent information"];
            [self.view.window addSubview:cancelView];
            [cancelView userSelectCancelReason:^(NSString *reason) {
               [self cancelOrderClick:order.order.order_id reason:reason success:^{
                   order.order.status = @6;
                   [tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationNone];
               }];
            }];
            
            
        }else if (footer.orderStatus == kOrderStatusReceived||footer.orderStatus == kOrderStatusComplete){
            //再买一次
            
        }
    }];
    
    footer.priceLbl.text = FormatString(@"$%@", order.order.needPayMoney);
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 44.0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    DDOrderSectionHeader *header = [[DDOrderSectionHeader alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 44)];
    DDOrderObj *order = self.orderSet.orderAry[section];
    if (order.orderItemGoodsList.count>0) {
        DDStoreObj *store = order.orderItemGoodsList[0].store;
        header.shopName = store.store_name;
    }
    header.orderStatus = [DDOrderInfo mappingOrderStatus:order.order.status];
    if (header.orderStatus == kOrderStatusReceived||header.orderStatus == kOrderStatusCancel||header.orderStatus == kOrderStatusComplete) {
        header.canDelete = YES;
    }else
        header.canDelete = NO;
    
    [header userDeleteOrderHandler:^{
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Confirm deletion of this order?" message:nil delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Delete", nil];
        [alert show];
        [alert click:^(NSInteger buttonIndex) {
            if (buttonIndex == 1) {
                [self deleteOrderClick:order.order.order_id success:^{
                    [self.orderSet.orderAry removeObject:order];
                    [tableView deleteSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationNone];
                }];
            }
        }];
    }];
    return header;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *indentifier = @"OrderCell";
    
    DDOrderTableCell *cell = [tableView dequeueReusableCellWithIdentifier:indentifier];
    
    if (!cell) {
        cell = [[DDOrderTableCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    DDOrderObj *order = self.orderSet.orderAry[indexPath.section];
    DDOrderObjItem *item = order.orderItemGoodsList[indexPath.row];
    [cell.goodsImage sd_setImageWithURL:[NSURL URLWithString:item.goods.small] placeholderImage:nil];
    cell.goodsNameLbl.text = item.goods.name;
    cell.priceLbl.text = FormatString(@"$%@", item.goods.price);
    
    NSString *addJson = ValidString(item.orderItem.addon);
    NSArray *addAry = [ToolKit JSONDecodeFromString:addJson];
    NSString *specString = @"";
    for (NSDictionary *dic in addAry) {
        NSString *key = dic[@"name"];
        NSString *value = dic[@"value"];
        specString = [specString stringByAppendingString:FormatString(@"%@:%@", key,value)];
        specString = [specString stringByAppendingString:@" "];
    }
    cell.goodsSizeLbl.text = specString;
    
    cell.countLbl.text = FormatString(@"×%@", item.orderItem.num);
    kOrderStatus orderStatus = [DDOrderInfo mappingOrderStatus:order.order.status];
    if (orderStatus == kOrderStatusReceived||orderStatus == kOrderStatusComplete) {
        if (item.orderItem.commentState.integerValue == 0) {
            cell.evaluateBtn.hidden = NO;
        }else{
            cell.evaluateBtn.hidden = YES;
        }
    }else{
        cell.evaluateBtn.hidden = YES;
    }
    [cell userEvaluateGoods:^{
       //评论商品
        DDEvaluateViewController *vc = StoryBoardViewController(@"Evaluate", @"DDEvaluateViewController");
        vc.goods = item.goods;
        [self.navigationController pushViewController:vc animated:YES];
    }];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    DDOrderDetailsViewController *details = StoryBoardViewController(@"Order", @"DDOrderDetailsViewController");
    DDOrderObj *order = self.orderSet.orderAry[indexPath.section];
    details.order = order;
    [self.navigationController pushViewController:details animated:YES];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.clickBlock) {
        alertView.clickBlock(buttonIndex);
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
